<template>
  <div>
    <!-- 文件主表管理 -->
    <el-form inline>
      <el-form-item prop="status">
        <el-select v-model="fileQuery.status" placeholder="请选择文件状态" style="width: 150px">
          <el-option label="全部" value=""></el-option>
          <el-option label="待转码" value="1"></el-option>
          <el-option label="可用" value="2"></el-option>
          <el-option label="转码失败" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="fileType">
        <el-select v-model="fileQuery.fileType" placeholder="请选择文件类型" style="width: 150px">
          <el-option label="全部" value=""></el-option>
          <el-option label="图片" value="1"></el-option>
          <el-option label="视频" value="2"></el-option>
          <el-option label="音频" value="3"></el-option>
          <el-option label="文档" value="4"></el-option>
          <el-option label="压缩包" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="scene">
        <el-select v-model="fileQuery.sceneCode" placeholder="请选择文件场景" style="width: 150px">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in sceneList" :key="item.id" :label="item.sceneCode" :value="item.sceneCode"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="bucket">
        <el-select v-model="fileQuery.bucketName" placeholder="请选择存储桶" style="width: 150px">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件场景" prop="scene">
        <el-input
            v-model="fileQuery.keyword"
            placeholder="搜索文件名/文件KEY"
            class="ml-4 w-60"
            @keyup.enter="loadFileData"
        >
          <template #append>
            <el-button icon="Search" @click="loadFileData"/>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="dialogVisible=true">新增文件</el-button>
    <el-button type="danger" >批量删除</el-button>
    <el-table :data="filePagination.list" stripe border >
      <el-table-column prop="fileKey" label="文件KEY"/>
      <el-table-column prop="originalName" label="文件名" />
      <el-table-column label="文件类型" >
        <template #default="{row}">
          <el-tag>{{ row.fileType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="fileSize" label="大小" width="100">
        <template #default="{row}">
          {{ formatFileSize(row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="fileStatusMap[row.status]?.type">
            {{ fileStatusMap[row.status]?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="uploaderId" label="上传者" width="120"/>
      <el-table-column prop="uploadTime" label="上传时间" width="180">
        <template #default="{row}">
          {{ formatDate(row.uploadTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{row}">
          <el-button size="small" @click="handlePreview(row)">预览</el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDeleteFile(row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="mt-4"
        v-model:current-page="fileQuery.pageNum"
        v-model:page-size="fileQuery.pageSize"
        :total="filePagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="loadFileData"
    />
    <el-dialog
        v-model="dialogVisible"
        title="文件上传"
        width="700"
    >
      <div>
        <el-form :model="fileUploadForm" ref="uploadFormRef" :rules="uploadRules">
          <el-form-item label="上传场景">
            <el-select v-model="fileUploadForm.sceneCode" placeholder="请选择上传场景">
              <el-option v-for="item in sceneList" :key="item.id" :label="item.sceneCode" :value="item.sceneCode">
                <span style="float: left">{{ item.sceneCode }}</span>
                <span style=" float: right;color: var(--el-text-color-secondary); font-size: 13px;">
                  {{ item.remark }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="fileUploadForm.fileType" placeholder="请选择文件类型">
              <el-option label="图片" :value="1"></el-option>
              <el-option label="视频" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件">
            <el-upload
                v-if="fileUploadForm.fileType === 1"
                v-model:file-list="fileList"
                :action="fileUpload"
                multiple
                :data="{sceneCode:fileUploadForm.sceneCode}"
                :on-preview="handlePreview"
                :limit="1"
            >
              <el-button type="primary"  :disabled="check">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500KB.
                </div>
              </template>
            </el-upload>
            <SplitChunkUpload v-else :scene-code="fileUploadForm.sceneCode"></SplitChunkUpload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  reqGetFilePage, reqDeleteFile,
  reqGetBucketList, reqUpdateBucket,
  reqGetSceneList, reqUpdateScene
} from '@/api/file'
import SplitChunkUpload from '@/components/uploader/SplitChunkUpload.vue'
import {fileUpload,formatDate} from '@/util'

let fileList=ref([])
const fileQuery = reactive({
  pageNum: 1,
  pageSize: 20,
  keyword: '',
  status: null,
  bucketName: null,
  sceneCode: null
})
let uploadFormRef = ref(null)
let dialogVisible = ref(false)
const filePagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
  list: []
})
let fileUploadForm=reactive({
  fileType:1,
  sceneCode: null
})
const fileStatusMap = {
  0: {label: '上传中', type: 'info'},
  1: {label: '待转码', type: 'warning'},
  2: {label: '可用', type: 'success'},
  3: {label: '转码失败', type: 'danger'},
  4: {label: '已删除', type: ''}
}
const bucketList = ref([])
const sceneList = ref([])

// 预览相关
const previewVisible = ref(false)
const currentFile = ref(null)

// 生命周期
onMounted(() => {
  loadFileData()
})

// 加载文件数据
const loadFileData = async () => {
  try {
    const res = await reqGetFilePage(fileQuery)
    Object.assign(filePagination, res.data)
  } catch (error) {
    ElMessage.error('加载文件数据失败')
  }
}
let getSceneList = async () => {
  try {
    const res = await reqGetSceneList()
    sceneList.value = res.data
  } catch (error) {
    ElMessage.error('加载场景列表失败')
  }
}
const handlePreview = (file) => {
  currentFile.value = file
  previewVisible.value = true
}
let check=computed(()=>{
  console.log("dayin ",!fileUploadForm.sceneCode)
  return !fileUploadForm.sceneCode;
})
// 处理删除文件
const handleDeleteFile = (file) => {
  ElMessageBox.confirm(`确定删除文件 ${file.originalName}?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await reqDeleteFile(file.id)
    ElMessage.success('文件已标记删除')
    await loadFileData()
  }).catch(() => null)
}

// 添加上传场景
const handleAddScene = () => {
  sceneDialog.current = {
    isPublic: 0,
    isEnabled: 1,
    maxFileSize: 10485760 // 默认10MB
  }
}

// 工具函数：格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i])
}

onMounted(()=>{
  getSceneList()
})
const uploadRules={
  fileType: [
    {required: true, message: '请选择文件类型', trigger: 'change'}
  ],
  sceneCode: [
    {required: true, message: '请选择上传场景', trigger: 'change'}
  ]
}
</script>

<style scoped>
.file-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.mb-4 {
  margin-bottom: 16px;
}

.ml-4 {
  margin-left: 16px;
}

.w-60 {
  width: 240px;
}

.file-restrictions {
  display: flex;
  align-items: center;
}
</style>
